const cloud = require('wx-server-sdk');

cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const {
    _id,
    partName,
    customerName,
    orderNumber,
    manufacturerNam,
    partImage,
    material,
    postprocessing,
    quantity,
    blankingImg,
    blankingTime,
    processingImage,
    processingTime,
    handleImage,
    handleTime,
    qualityImg,
    qualityTime,
    deliveryTime,
    remarks,
    afterSale,
    sendImage,
  } = event;

  try {
    // 查询当前订单是否存在
    const orderRes = await db.collection('Order').where({
      orderNumber: orderNumber
    }).get();

    let existingManufactors = [];

    if (orderRes.data.length > 0) {
      // 如果订单存在，查看订单中的厂家字段是否包含前端传入的厂家名
      existingManufactors = orderRes.data[0].manufactor || [];

      if (!existingManufactors.includes(manufacturerNam)) {
        // 如果厂家名不存在订单的厂家字段中，添加厂家名到订单的厂家数组中
        existingManufactors.push(manufacturerNam);

        // 更新订单的厂家字段
        await db.collection('Order').doc(orderRes.data[0]._id).update({
          data: {
            manufactor: existingManufactors
          }
        });
      }
    } else {
      // 如果订单不存在，可以根据实际情况返回错误信息或进行其他处理
      return {
        success: false,
        errorMessage: '订单不存在'
      };
    }

    // 查询要修改的零件信息
    const partRes = await db.collection('Parts').doc(_id).get();

    if (!partRes.data) {
      return {
        success: false,
        errorMessage: '未找到要修改的零件信息'
      };
    }

    // 更新零件信息
    const updateRes = await db.collection('Parts').doc(_id).update({
      data: {
        partName,
        customerName,
        orderNumber,
        manufacturerNam,
        partImage,
        quantity,
        blankingImg,
        blankingTime,
        processingImage,
        processingTime,
        handleImage,
        handleTime,
        qualityImg,
        qualityTime,
        deliveryTime,
        remarks,
        afterSale,
        sendImage,
        material,
        postprocessing,
        updatedAt: new Date() // 更新时间
      }
    });

    if (updateRes.stats.updated === 1) {
      return {
        success: true,
        message: '零件信息更新成功'
      };
    } else {
      return {
        success: false,
        message: '未能成功更新零件信息'
      };
    }
  } catch (err) {
    console.error('Error updating part information:', err);
    return {
      success: false,
      errorMessage: err.message
    };
  }
};
